<template>
  <el-card class="visit-inner-box" v-if="visible">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="left">
      <el-row class="form-item-row">
        <el-col :span="24">
          <picker-view v-model="ruleForm.brand_id" type="company" placeholder="请选择品牌"></picker-view>

          <el-select class="ml10" v-model="ruleForm.status" placeholder="请选择跟进状态" @change="changeStatus">
            <el-option v-for="(item,key) in statusList" :key="key" :label="item.title" :value="item.id"></el-option>
          </el-select>

          <el-select class="ml10"  placeholder="请选择原因" @change="changeFast">
            <el-option v-for="item in fastList" :key="item" :label="item" :value="item"></el-option>
          </el-select>

          <el-date-picker class="ml10" v-if="isShowNextVisit" type="datetime" v-model="ruleForm.next_visit_time"
                          placeholder="请选择下次回访时间" value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-col>
      </el-row>

      <el-row class="form-item-row">
        <el-col :span="24">
          <el-input v-model="ruleForm.remark" type="textarea" placeholder="请填写跟进记录"></el-input>
        </el-col>
      </el-row>

      <el-row class="form-item-row" v-if="fileGroup.image.length > 0">
        <el-col :span="24" class="image-group">
          <div class="image-box" v-for="(item,key) in fileGroup.image" :key="key">
            <el-image :src="item.url" fit="contain" :preview-src-list="uploadImages"></el-image>

            <el-button class="remove" type="warning" size="mini" icon="el-icon-close" circle
                       @click="handleRemove(item, 'image')"
            ></el-button>
          </div>
        </el-col>
      </el-row>

      <el-row class="form-item-row" v-if="fileGroup.file.length > 0">
        <el-col :span="24">
          <el-table :data="fileGroup.file">
            <el-table-column label="文件" prop="name"></el-table-column>
            <el-table-column align="right">
              <template slot-scope="scope">
                <el-link type="text" :href="scope.row.url" target="_blank" v-if="scope.row.ext == 'pdf'"><i
                  class="el-icon-view"
                ></i></el-link>
                <el-link type="text" :href="scope.row.url" target="_blank" v-else><i class="el-icon-download"></i>
                </el-link>
                <el-button type="text" icon="el-icon-close" class="ml10" @click="handleRemove(scope.row, 'file')"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <el-row class="form-item-row">
        <el-col :span="12">
          <el-upload ref="uploadRef" :action="uploadAction" :headers="uploadHeader" :show-file-list="false"
                     :file-list="fileList" list-type="picture" :on-success="uploadSuccess"
          >
            <el-button size="small" type="text" icon="el-icon-link">附件</el-button>
          </el-upload>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-button size="mini" @click="cancel">取消</el-button>
          <el-button type="primary" size="mini" @click="submit">发布</el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</template>

<script>
import {
  getToken
} from '@/utils/auth'

import {
  createVisitApi
} from '@/api/customer/visit.js'
import {
  getPickerApi
} from '@/api/system/dictionary/status.js'
import uploadFiles from '@/components/upload/files.vue'
import pickerView from '@/components/picker/select.vue'

const ruleForm = {
  member_id: '',
  status: '',
  invalid: '',
  next_visit_time: '',
  files: [],
  remark: ''
}

export default {
  inject: {
    pageIndex: {
      default: () => null
    }
  },
  components: {
    uploadFiles,
    pickerView
  },
  data() {
    return {
      visible: false,
      fileList: [],
      fileGroup: {
        image: [],
        file: []
      },
      statusList: [],
      fastList: [],
      ruleForm: Object.assign({}, ruleForm),
      rules: {
        status: [{
          required: true,
          message: '请选择跟进状态',
          trigger: 'change'
        }],
        remark: [{
          required: true,
          message: '请填写备注',
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    isShowNextVisit() {
      let target = this.statusList.find(ele => ele.id == this.ruleForm.status)
      if (!target) return false

      return target.need_next_visit == 1 ? true : false
    },
    invalidList() {
      let localData = localStorage.getItem('invalidPickerList')
      if (localData) {
        return JSON.parse(localData)
      } else {
        return []
      }
    },
    uploadImages() {
      return this.fileGroup.image.map(item => item.url)
    },
    uploadAction: function() {
      return process.env.VUE_APP_BASE_API + '/api/system.file/upload'
    },
    uploadHeader: function() {
      let header = {}
      header['X-Token'] = getToken()
      return header
    }
  },
  methods: {
    showDrawer(member_id) {
      this.ruleForm = Object.assign({}, ruleForm)
      this.ruleForm.member_id = member_id
      this.ruleForm.files = []
      this.fileList = []
      this.fileGroup = {
        image: [],
        file: []
      }
      this.visible = true
      this.getStatusPicker()
      this.$nextTick(() => {
        this.$refs['uploadRef'].clearFiles()
      })
  
    },
    getStatusPicker() {
      getPickerApi({}).then(res => {
        this.statusList = res.data.list
      })
    },
    cancel() {
      this.visible = false
      this.$emit('hideInnerVisit')
    },
    changeStatus(e) {
      let target = this.statusList.find(ele => ele.id == this.ruleForm.status)
      this.fastList = target.fast
    },
    changeFast(ele) {
      this.ruleForm.remark += ele
    },
    uploadSuccess(res, file) {
      // 获取文件类型;
      // 根据file规则构建新的对象

      const newFile = {
        ext: res.data.extname,
        name: file.name,
        url: res.data.path
        // 其他属性根据需要添加
      }
      // 将新的文件对象添加到fileList中
      this.fileList.push(newFile)
      // 判断是否是图片类型, 则添加到fileGroup中的image数组中
      let imageTypes = ['png', 'jpg', 'jpeg', 'gif']
      if (imageTypes.includes(newFile.ext.toLowerCase())) {
        this.fileGroup.image.push(newFile)
      } else {
        // 如果是文件类型, 则添加到fileGroup中的file数组中
        this.fileGroup.file.push(newFile)
      }
    }
    ,
    handleRemove(file, type) {
      // 提醒确认删除
      this.$confirm('删除文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 处理移除逻辑...
          const index = this.fileList.findIndex(item => item.url === file.url)
          if (index !== -1) {
            // 删除文件
            this.fileList.splice(index, 1)
          }

          if (type == 'image') {
            const index = this.fileGroup.image.findIndex(item => item.url === file.url)
            if (index !== -1) {
              // 删除文件
              this.fileGroup.image.splice(index, 1)
            }
          } else {
            // 如果是文件类型, 则添加到fileGroup中的file数组中
            const index = this.fileGroup.file.findIndex(item => item.url === file.url)
            if (index !== -1) {
              // 删除文件
              this.fileGroup.file.splice(index, 1)
            }
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
    ,
    submit() {
      let _this = this
      this.ruleForm.files = this.fileList

      let target = this.statusList.find(ele => ele.id == this.ruleForm.status)
      if (target.need_next_visit == 1 && !this.ruleForm.next_visit_time && this.ruleForm.status != 10) {
        this.$message.warning('请选择下次回访时间')
        return false
      }

      this.$refs['ruleForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        let data = Object.assign({}, _this.ruleForm)

        // 添加客资
        createVisitApi(data).then((res) => {
          if (res.code == '200') {
            _this.$message.success(res.msg)
            _this.visible = false
            _this.$emit('reload')
            _this.$emit('hideInnerVisit')
            if (this.pageIndex) _this.pageIndex.getTableData()
          } else {
            _this.$message.warning(res.msg)
          }
        })
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.visit-inner-box {
  .form-item-row {
    margin-bottom: 12px;

    .image-group {
      // grid 布局，5列2行，第二行没有的时候不显示
      display: grid;
      grid-template-columns: repeat(10, 1fr);
      grid-gap: 10px;

      .image-box {
        height: 100px;
        border-radius: 4px;
        border: 1px solid #dedede;
        position: relative;

        .el-image {
          width: 100%;
          height: 100%;
        }

        .remove {
          display: none;
          position: absolute;
          top: 10px;
          right: 10px;
        }

        &:hover {
          .remove {
            display: block;
          }
        }
      }

    }
  }

  .form-item-row:last-child {
    margin-bottom: 0;
  }

  .ml10 {
    margin-left: 10px;
  }
}
</style>
